import { _decorator, Component, Node, UITransform, screen, view } from 'cc';
import { AppControll } from './AppControll';
const { ccclass, property } = _decorator;



@ccclass('AdCompont')
export class AdCompont extends Component {
    @property(Boolean)
    bIsHide: boolean = false;
    @property(Number)
    nChangeTime: number = 10;

    private strNodeBanner = "adBanner";
    private strMate = "adGrid";
    private bCurHide: boolean = true;
    private nCurTime: number = 0;

    protected onLoad(): void {
        this.RegisterBtnEvent();
    }

    protected start(): void {
        this.CreateAd();
    }

    RegisterBtnEvent() {
    }

    CreateAd() {
        let tempB = this.node.getChildByName(this.strNodeBanner);
        let tempM = this.node.getChildByName(this.strMate);
        if (tempB) {
            console.log("CreateAd");
            AppControll.Platform.CreateBanner(this.ConverPos(tempB));
        }
        if (tempM) {
            AppControll.Platform.CreateCustomAd(this.ConverPos(tempM));
        }
    }

    ConverPos(node: Node): any {
        let rSize = { x: 0, y: 0, width: 0, height: 0 };
        //获取小游戏屏幕像素分辨率
        let size = view.getFrameSize();
        let vSize = view.getVisibleSize();
        let nodeSize = node.getComponent(UITransform).contentSize;
        //获取目标Y轴位置在总分辨率比例
        let tempY = 0.5 - node.position.y / vSize.height;
        let tempX = 0.5 + node.position.x / vSize.width;
        rSize.x = size.width * tempX - nodeSize.width / 2;
        rSize.y = size.height * tempY - nodeSize.height / 2;
        rSize.width = nodeSize.width;
        rSize.height = nodeSize.height;
        return rSize;
    }

    protected onDisable(): void {
        AppControll.Platform.DestoryBanner();
        AppControll.Platform.DestoryCustom();
    }

    protected onDestroy(): void {

    }

    protected update(dt: number): void {
        if (!this.bIsHide) return;
        this.nCurTime += dt;
        if (Math.floor(this.nCurTime) >= this.nChangeTime) {
            this.nCurTime = 0;
            this.bCurHide = !this.bCurHide;
            if (this.bCurHide) {
                this.CreateAd();
            } else {
                AppControll.Platform.DestoryBanner();
                AppControll.Platform.DestoryCustom();
            }
        }

    }
}


